<template>
    <div class="article-container">
      <!-- 导航栏 -->
      <van-nav-bar
        class="page-nav-bar"
        left-arrow
        title="黑马头条"
        @click-left="$router.back()"
      ></van-nav-bar>
      <!-- /导航栏 -->
  
      <div class="main-wrap">
        <!-- 加载中 -->
        <div class="loading-wrap" v-if="loading">
          <van-loading
            color="#3296fa"
            vertical
          >加载中</van-loading>
        </div>
        <!-- /加载中 -->
  
        <!-- 加载完成-文章详情 -->
        <div class="article-detail" v-else-if="article.title">
          <!-- 文章标题 -->
          <h1 class="article-title">{{article.title}}</h1>
          <!-- /文章标题 -->
  
          <!-- 用户信息 -->
          <van-cell class="user-info" center :border="false">
            <van-image
              class="avatar"
              slot="icon"
              round
              fit="cover"
              :src="article.aut_photo"
            />
            <div slot="title" class="user-name">{{article.aut_name}}</div>
            <div slot="label" class="publish-date">{{article.pubdate | dayFn}}</div>
            <!-- 
                $event是事件参数
                当我们传递给子组件的数据既要使用还要修改
                    传递：props
                        :is_followed="article.is_followed"
                    修改：自定义事件
                    @update_is_followed="article.is_followed = $event"
                简写方式: 在组件上使用v-model
                    v-model相当于：value='article.is_followed' @input="article.is_followed = $event"
                
                    一个组件只能使用一个v-model
                    
                如果需要修改v-model的规则名称，可以通过子组件的model属性修改
                    可以使用属性的.sync修饰符
             -->
            <followUsert 
                class="follow-btn"
                :user_id="article.aut_id"
                v-model="article.is_followed"
            />
            <!-- <van-button
              v-if="article.is_followed"
              class="follow-btn"
              round
              size="small"
              @click="onFollow"
              :loading="followLoading"
            >已关注</van-button>
            <van-button
              v-else
              class="follow-btn"
              type="info"
              color="#3296fa"
              round
              size="small"
              icon="plus"
              @click="onFollow"
              :loading="followLoading"
            >关注</van-button> -->
            
          </van-cell>
          <!-- /用户信息 -->
  
          <!-- 文章内容 -->
          <div class="article-content markdown-body"
            v-html="article.content"
            ref="article-content"
            :lock-scroll="true"
            ></div>
          <van-divider>正文结束</van-divider>

          <!-- 文章评论 -->
          <commentList
            :sourceID="article.art_id"
            :list="commentLists"
            @reply_click="onReplyClick"
            @onload_success="(totalCommentCount = $event.total_count)"
          />
          <!-- /文章评论 -->
            
          <!-- 底部区域 -->
          <div class="article-bottom">
            <van-button
              class="comment-btn"
              type="default"
              round
              size="small"
              @click="(isPopupShow=true)"
            >写评论</van-button>
            <van-icon
              name="comment-o"
              :info="totalCommentCount"
              color="#777"
            />
            <CollectArticle
              v-model="article.is_collected"
              :articleID="article.art_id"
            />
            <!-- <van-icon
              color="#777"
              name="star-o"
            /> -->
            <LikeArticle 
              v-model="article.attitude"
              :articleID="article.art_id"
            />
            <!-- <van-icon
              color="#777"
              name="good-job-o"
            /> -->
            <van-icon name="share" color="#777777"></van-icon>
          </div>
          <!-- /底部区域 -->

          <!-- 发布评论弹出窗 -->
          <van-popup 
            v-model="isPopupShow" 
            position="bottom" 
          >
          <commentPost
          :target="article.art_id"
          @pl_success="onPostSuccess"
          />
          </van-popup>

        </div>
        <!-- /加载完成-文章详情 -->
  
        <!-- 加载失败：404 -->
        <div class="error-wrap" v-else-if="errStatus === 404">
          <van-icon name="failure" />
          <p class="text">该资源不存在或已删除！</p>
        </div>
        <!-- /加载失败：404 -->
  
        <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
        <div class="error-wrap" v-else>
          <van-icon name="failure" />
          <p class="text">内容加载失败！</p>
          <van-button class="retry-btn" 
            @click="loadArticle"
            >点击重试</van-button>
        </div>
        <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
      </div>

      <!-- 弹出层是懒加载，且只有在第一次展示才会渲染 -->
      <!-- 评论回复 -->
      <van-popup 
          v-model="isReplyshow" 
          position="bottom" 
          style="height:90%"
      >
      <!-- 通过v-if使的弹出层每次都重新进行渲染 -->
      <commentReply
        v-if="isReplyshow"
        :comment="currentComment"
        @close="isReplyshow = false"
      />
      </van-popup>
    </div>
  </template>
  
  <script>
  import {getArticleById} from '@/api/article'
  import { ImagePreview } from 'vant'
  import followUsert from '@/components/follow-user/index.vue'
  import CollectArticle from '@/components/collect-article/index.vue'
  import LikeArticle from '@/components/like-article/index.vue'
  import commentList from './components/comment-list.vue'
  import commentPost from './components/comment-post.vue'
  import commentReply from './components/comment-reply.vue'
  export default {
    name: 'ArticleIndex',
    components: {
        followUsert,
        CollectArticle,
        LikeArticle,
        commentList,
        commentPost,
        commentReply
    },
    props: {
      articleId: {
        type: [Number, String, Object],
        required: true
      }
    },
    //给所有的后代提供数据
    provide:function(){
      return{
        articleID:this.articleId
      }
    },
    data () {
      return {
        article:{}, //文章详情
        loading: true, //加载中的loading状态
        errStatus: 0, //失败的状态码
        followLoading: false,
        totalCommentCount: 0,
        isPopupShow: false, //评论弹出窗
        commentLists:[], //评论列表
        isReplyshow:false, //回复弹窗
        currentComment:{} //当前点击回复的评论项
      }
    },
    computed: {},
    watch: {},
    created () {
        this.loadArticle()
    },
    mounted () {},
    methods: {
        async loadArticle(){
            this.loading = true
            try{
                const {data} = await getArticleById(this.articleId)
                // if(Math.random()*1 > 0.5){
                //     JSON.parse('axagxga')
                // }

                //数据驱动视图不是立即的
                this.article = data.data

                //初始化图片点击预览
                
                setTimeout(()=>{
                    this.previewImage()
                },200)
                
            }catch(err){
                if(err.response && err.response.status === 404){
                    this.errStatus = 404
                }
                this.$toast('获取数据失败',err)
            }
            //请求成功或失败 关闭loading
            this.loading = false
        },
        previewImage(){
            //得到所有image节点
            const articleContent = this.$refs['article-content']
            const imgs = articleContent.querySelectorAll('img')

            //获取所有img地址
            const imgUrl = []
            imgs.forEach((el,index) => {
                imgUrl.push(el.src)
                //给每个Img注册点击事件
                el.onclick = ()=>{
                    ImagePreview({
                        //预览的图片地址数组
                        images: imgUrl,
                        //起始位置
                        startPosition: index,
                        closeable: true,
                        showIndicators: true,
                        loop: false
                    })
                }
            })
        },
        onPostSuccess(val){
            //关闭弹出层
            this.isPopupShow = false
            //将发布内容显示到评论列表顶部
            this.commentLists.unshift(val.new_obj)
        },
        onReplyClick(el){
          this.currentComment = el
          //显示评论回复弹出层
          this.isReplyshow  = true
        }

        
    }
  }
  </script>
  
  <style scoped lang="less">
  @import './github-markdown.css';
  .article-container {
    .main-wrap {
      position: fixed;
      left: 0;
      right: 0;
      top: 92px;
      bottom: 88px;
      overflow-y: scroll;
      background-color: #fff;
    }
    .article-detail {
      .article-title {
        font-size: 40px;
        padding: 50px 32px;
        margin: 0;
        color: #3a3a3a;
      }
  
      .user-info {
        padding: 0 32px;
        .avatar {
          width: 70px;
          height: 70px;
          margin-right: 17px;
        }
        .van-cell__label {
          margin-top: 0;
        }
        .user-name {
          font-size: 24px;
          color: #3a3a3a;
        }
        .publish-date {
          font-size: 23px;
          color: #b7b7b7;
        }
        .follow-btn {
          width: 170px;
          height: 58px;
        }
      }
  
      .article-content {
        padding: 55px 32px;
        /deep/ p {
          text-align: justify;
        }
      }
    }
  
    .loading-wrap {
      padding: 200px 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #fff;
    }
  
    .error-wrap {
      padding: 200px 32px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background-color: #fff;
      .van-icon {
        font-size: 122px;
        color: #b4b4b4;
      }
      .text {
        font-size: 30px;
        color: #666666;
        margin: 33px 0 46px;
      }
      .retry-btn {
        width: 280px;
        height: 70px;
        line-height: 70px;
        border: 1px solid #c3c3c3;
        font-size: 30px;
        color: #666666;
      }
    }
  
    .article-bottom {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: space-around;
      align-items: center;
      box-sizing: border-box;
      height: 88px;
      border-top: 1px solid #d8d8d8;
      background-color: #fff;
      .comment-btn {
        width: 282px;
        height: 46px;
        border: 2px solid #eeeeee;
        font-size: 30px;
        line-height: 46px;
        color: #a7a7a7;
      }
      /deep/.van-icon{
        font-size: 40px;
        .van-info {
          font-size: 16px;
          background-color: #e22829;
        }
      }
    }
  }
  </style>
  